<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/24
 * Time: 8:26
 */
require_once DXW_QINIU_DIR . 'autoload.php';
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use \Qiniu\Cdn\CdnManager;

class Qiniu{
    static public function upload($filepath,$fat,$key=null){
        $accessKey = DXW_QINIU_AK;
        $secretKey =DXW_QINIU_SK;
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        // 要上传的空间
        $bucket = DXW_QINIU_NAMESPACE;
        // 生成上传 Token
        $token = $auth->uploadToken($bucket);
        // 上传到七牛后保存的文件名
        $t = time().rand(1,100);
        $key = $key ? $key : md5($t).".".$fat;
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        $filepath = str_replace("//", '/', $filepath);
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filepath);

        if ($err !== null) {
            return array();
        } else {
            $ret["key"] = DXW_QINIU_URL_KEY.$ret["key"];
            @unlink($filepath);
            return $ret;
        }
    }
    static function get_token(){
        $accessKey = DXW_QINIU_AK;
        $secretKey =DXW_QINIU_SK;
        $bucket = DXW_QINIU_NAMESPACE;
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucket);
        return $token;
    }
    static public function recover($filepath,$key){
        $accessKey = DXW_QINIU_AK;
        $secretKey =DXW_QINIU_SK;
        $bucket = DXW_QINIU_NAMESPACE;
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        $config = new \Qiniu\Config();
        $bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);
        $bucketManager->delete($bucket, $key);
        return self::upload($filepath,"",$key);
    }
}